﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlServerCe;

namespace eWallet.Data.Local.eWalletDataSetTableAdapters
{
	public partial class GroupsTableAdapter
	{

		/// <summary>
		/// Creates a new instance of the table adapter and specifies the full file
		/// path to the SQL Server Compact Edition database to connect to.
		/// </summary>
		/// <param name="dbPath">The full file path to the database file.</param>
		public GroupsTableAdapter(string dbPath)
		{
			this._connection = new SqlCeConnection(string.Format("Data Source={0}", dbPath));
		}



		/// <summary>
		/// Fills the given table with the row whose ID matches the given value.
		/// </summary>
		/// <param name="table">The table to fill.</param>
		/// <param name="groupId">The ID of the group to fill.</param>
		/// <returns>Returns the number of filled rows.</returns>
		public int Fill(eWalletDataSet.GroupsDataTable table, Guid groupId)
		{
			int i = 0;

			using (SqlCeConnection conn = new SqlCeConnection(this.Connection.ConnectionString))
			{
				using (SqlCeCommand cmd = new SqlCeCommand("SELECT * FROM [Groups] WHERE [Id] = @Id", conn))
				{
					cmd.Parameters.AddWithValue("@Id", groupId);
					using (SqlCeDataAdapter adr = new SqlCeDataAdapter(cmd))
					{
						i = adr.Fill(table);
					}
				}
			}
			return i;
		}

		/// <summary>
		/// Fills the given table with groups that are not used, i.e. no secrets belong to the group.
		/// </summary>
		/// <param name="table">The table to fill.</param>
		/// <returns></returns>
		public int FillUnused(eWalletDataSet.GroupsDataTable table)
		{
			if (null == table)
				throw new ArgumentNullException("table");

			if (this.ClearBeforeFill)
				table.Clear();

			int i = 0;

			using (SqlCeCommand cmd = new SqlCeCommand("SELECT * FROM [Groups] WHERE [Id] NOT IN (SELECT [GroupId] FROM [Secrets])", this.Connection))
			{
				using (SqlCeDataAdapter adr = new SqlCeDataAdapter(cmd))
				{
					i = adr.Fill(table);
				}
			}

			return i;
		}

		public eWalletDataSet.GroupsDataTable GetData(Guid groupId)
		{
			eWalletDataSet.GroupsDataTable table = new eWalletDataSet.GroupsDataTable();
			this.Fill(table, groupId);
			return table;
		}

		public eWalletDataSet.GroupsDataTable GetUnusedData()
		{
			eWalletDataSet.GroupsDataTable table = new eWalletDataSet.GroupsDataTable();
			this.FillUnused(table);
			return table;
		}

	}
}
